import cv2
import numpy as np
import os


#folder_path = "image"  # 替换为你的文件夹路径
#
#for root, dirs, files in os.walk(folder_path):
#    for file in files:
#        file_name = os.path.join(root, file)
#        print(file_name)  # 这里可以对每个文件进行你想要的操作
 
# 读取图片
image = cv2.imread("a1.png")

# 将图像转换为灰度图像
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# 使用自适应阈值将图像转换为二值图像
thresh = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV, 11, 4)

# 使用形态学操作来关闭图像的边缘
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
closed = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)

# 查找图像中的轮廓
contours, _ = cv2.findContours(closed.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# 文件序号计数器归零
counter = 0
# 遍历每个轮廓
for contour in contours:
    # 计算轮廓的边界框
    x, y, w, h = cv2.boundingRect(contour)
    
    # 过滤掉过小的边界框
    if w > 100 and h > 100:
        # 裁剪图像中的内容区块,每边各加宽10px
        block = image[y-10:y+h+10, x-10:x+w+10]
        
        # 文件序号计数器加一
        counter += 1

        cv2.imwrite((str(counter) + '.jpg'), block)
        # 显示裁剪后的内容区块
        #cv2.imshow("Content Block", block)
        #cv2.waitKey(0)

# 关闭窗口
cv2.destroyAllWindows()
